<template>
  <div class="notification-rule">
    <!-- 搜索和操作栏 -->
    <div class="operation-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="规则名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入规则名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="消息类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择消息类型"
            clearable
          >
            <el-option
              v-for="type in messageTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="启用" value="enabled" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="operation-buttons">
        <el-button type="primary" @click="handleCreate">
          创建规则
        </el-button>
        <el-button
          type="danger"
          :disabled="!selectedRules.length"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
        <el-button
          type="success"
          :disabled="!selectedRules.length"
          @click="handleBatchEnable"
        >
          批量启用
        </el-button>
        <el-button
          type="warning"
          :disabled="!selectedRules.length"
          @click="handleBatchDisable"
        >
          批量禁用
        </el-button>
      </div>
    </div>

    <!-- 规则列表 -->
    <el-card class="rule-table">
      <el-table
        :data="ruleList"
        border
        v-loading="tableLoading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="规则名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="type" label="消息类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ getMessageTypeLabel(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100" sortable>
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)">
              {{ getPriorityLabel(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="channels" label="通知渠道" width="200">
          <template #default="{ row }">
            <el-tag
              v-for="channel in row.channels"
              :key="channel"
              class="channel-tag"
              :type="getChannelType(channel)"
            >
              {{ getChannelLabel(channel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="condition" label="触发条件" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tooltip
              :content="formatCondition(row.condition)"
              placement="top"
              :show-after="500"
            >
              <span>{{ formatCondition(row.condition) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="'enabled'"
              :inactive-value="'disabled'"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" sortable />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="primary" link @click="handleCopy(row)">
              复制
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 规则表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '创建规则' : '编辑规则'"
      width="800px"
      destroy-on-close
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="ruleRules"
        label-width="120px"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="消息类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择消息类型">
            <el-option
              v-for="type in messageTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="ruleForm.priority" placeholder="请选择优先级">
            <el-option label="紧急" value="urgent" />
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item label="通知渠道" prop="channels">
          <el-checkbox-group v-model="ruleForm.channels">
            <el-checkbox label="email">邮件</el-checkbox>
            <el-checkbox label="sms">短信</el-checkbox>
            <el-checkbox label="wecom">企业微信</el-checkbox>
            <el-checkbox label="dingtalk">钉钉</el-checkbox>
            <el-checkbox label="feishu">飞书</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="触发条件" prop="condition">
          <div class="condition-builder">
            <el-select
              v-model="ruleForm.condition.type"
              placeholder="请选择条件类型"
              @change="handleConditionTypeChange"
            >
              <el-option label="时间触发" value="time" />
              <el-option label="事件触发" value="event" />
              <el-option label="数据触发" value="data" />
              <el-option label="组合条件" value="combination" />
            </el-select>
            
            <!-- 时间触发条件 -->
            <template v-if="ruleForm.condition.type === 'time'">
              <el-select v-model="ruleForm.condition.timeType" placeholder="请选择时间类型">
                <el-option label="固定时间" value="fixed" />
                <el-option label="周期时间" value="period" />
                <el-option label="相对时间" value="relative" />
              </el-select>
              <template v-if="ruleForm.condition.timeType === 'fixed'">
                <el-date-picker
                  v-model="ruleForm.condition.time"
                  type="datetime"
                  placeholder="请选择时间"
                />
              </template>
              <template v-else-if="ruleForm.condition.timeType === 'period'">
                <el-select v-model="ruleForm.condition.period" placeholder="请选择周期">
                  <el-option label="每天" value="daily" />
                  <el-option label="每周" value="weekly" />
                  <el-option label="每月" value="monthly" />
                </el-select>
                <el-time-picker
                  v-model="ruleForm.condition.time"
                  placeholder="请选择时间"
                />
              </template>
              <template v-else>
                <el-input-number
                  v-model="ruleForm.condition.relativeValue"
                  :min="1"
                  placeholder="数值"
                />
                <el-select v-model="ruleForm.condition.relativeUnit" placeholder="请选择单位">
                  <el-option label="分钟" value="minutes" />
                  <el-option label="小时" value="hours" />
                  <el-option label="天" value="days" />
                </el-select>
              </template>
            </template>

            <!-- 事件触发条件 -->
            <template v-if="ruleForm.condition.type === 'event'">
              <el-select v-model="ruleForm.condition.event" placeholder="请选择事件">
                <el-option
                  v-for="event in eventOptions"
                  :key="event.value"
                  :label="event.label"
                  :value="event.value"
                />
              </el-select>
            </template>

            <!-- 数据触发条件 -->
            <template v-if="ruleForm.condition.type === 'data'">
              <el-select v-model="ruleForm.condition.field" placeholder="请选择字段">
                <el-option
                  v-for="field in fieldOptions"
                  :key="field.value"
                  :label="field.label"
                  :value="field.value"
                />
              </el-select>
              <el-select v-model="ruleForm.condition.operator" placeholder="请选择操作符">
                <el-option label="等于" value="eq" />
                <el-option label="不等于" value="ne" />
                <el-option label="大于" value="gt" />
                <el-option label="小于" value="lt" />
                <el-option label="包含" value="contains" />
                <el-option label="不包含" value="notContains" />
              </el-select>
              <el-input
                v-model="ruleForm.condition.value"
                placeholder="请输入值"
              />
            </template>

            <!-- 组合条件 -->
            <template v-if="ruleForm.condition.type === 'combination'">
              <el-select v-model="ruleForm.condition.logic" placeholder="请选择逻辑关系">
                <el-option label="且" value="and" />
                <el-option label="或" value="or" />
              </el-select>
              <div
                v-for="(condition, index) in ruleForm.condition.conditions"
                :key="index"
                class="sub-condition"
              >
                <el-button
                  type="danger"
                  link
                  @click="removeSubCondition(index)"
                >
                  删除
                </el-button>
                <el-select
                  v-model="condition.type"
                  placeholder="请选择条件类型"
                  @change="handleSubConditionTypeChange(index)"
                >
                  <el-option label="时间触发" value="time" />
                  <el-option label="事件触发" value="event" />
                  <el-option label="数据触发" value="data" />
                </el-select>
                <!-- 子条件配置（与主条件类似） -->
              </div>
              <el-button type="primary" link @click="addSubCondition">
                添加条件
              </el-button>
            </template>
          </div>
        </el-form-item>

        <el-form-item label="重试策略" prop="retryStrategy">
          <el-switch
            v-model="ruleForm.retryStrategy.enabled"
            @change="handleRetryStrategyChange"
          />
          <template v-if="ruleForm.retryStrategy.enabled">
            <div class="retry-strategy">
              <el-form-item label="最大重试次数" prop="retryStrategy.maxRetries">
                <el-input-number
                  v-model="ruleForm.retryStrategy.maxRetries"
                  :min="1"
                  :max="10"
                />
              </el-form-item>
              <el-form-item label="重试间隔" prop="retryStrategy.interval">
                <el-input-number
                  v-model="ruleForm.retryStrategy.interval"
                  :min="1"
                  :max="60"
                />
                <span class="unit">分钟</span>
              </el-form-item>
              <el-form-item label="失败处理" prop="retryStrategy.failureAction">
                <el-select v-model="ruleForm.retryStrategy.failureAction">
                  <el-option label="通知管理员" value="notify" />
                  <el-option label="降级处理" value="degrade" />
                  <el-option label="忽略" value="ignore" />
                </el-select>
              </el-form-item>
            </div>
          </template>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="ruleForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRule" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getRuleList,
  createRule,
  updateRule,
  deleteRule,
  updateRuleStatus,
  batchDeleteRules,
  batchUpdateRuleStatus
} from '@/api/message'

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: ''
})

// 表格数据
const ruleList = ref([])
const tableLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedRules = ref([])

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('create')
const ruleFormRef = ref(null)
const saving = ref(false)

// 规则表单
const ruleForm = reactive({
  name: '',
  type: '',
  priority: 'medium',
  channels: [],
  condition: {
    type: '',
    timeType: '',
    time: null,
    period: '',
    relativeValue: 1,
    relativeUnit: 'minutes',
    event: '',
    field: '',
    operator: '',
    value: '',
    logic: 'and',
    conditions: []
  },
  retryStrategy: {
    enabled: false,
    maxRetries: 3,
    interval: 5,
    failureAction: 'notify'
  },
  remark: ''
})

// 表单验证规则
const ruleRules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择消息类型', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  channels: [
    { required: true, message: '请选择通知渠道', trigger: 'change' },
    { type: 'array', min: 1, message: '至少选择一个通知渠道', trigger: 'change' }
  ],
  condition: [
    { required: true, message: '请配置触发条件', trigger: 'change' }
  ]
}

// 消息类型选项
const messageTypes = [
  { label: '系统通知', value: 'system' },
  { label: '业务通知', value: 'business' },
  { label: '告警通知', value: 'alert' },
  { label: '提醒通知', value: 'reminder' }
]

// 事件选项
const eventOptions = [
  { label: '用户登录', value: 'user_login' },
  { label: '数据变更', value: 'data_change' },
  { label: '系统异常', value: 'system_error' },
  { label: '任务完成', value: 'task_complete' }
]

// 字段选项
const fieldOptions = [
  { label: '用户ID', value: 'userId' },
  { label: '用户名', value: 'username' },
  { label: '状态', value: 'status' },
  { label: '数量', value: 'count' }
]

// 初始化
onMounted(() => {
  loadRuleList()
})

// 加载规则列表
const loadRuleList = async () => {
  tableLoading.value = true
  try {
    const res = await getRuleList({
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    })
    ruleList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取规则列表失败:', error)
    ElMessage.error('获取规则列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadRuleList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRules.value = selection
}

// 处理状态变更
const handleStatusChange = async (row) => {
  try {
    await updateRuleStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
    row.status = row.status === 'enabled' ? 'disabled' : 'enabled'
  }
}

// 处理创建
const handleCreate = () => {
  dialogType.value = 'create'
  Object.keys(ruleForm).forEach(key => {
    if (key === 'condition') {
      ruleForm[key] = {
        type: '',
        timeType: '',
        time: null,
        period: '',
        relativeValue: 1,
        relativeUnit: 'minutes',
        event: '',
        field: '',
        operator: '',
        value: '',
        logic: 'and',
        conditions: []
      }
    } else if (key === 'retryStrategy') {
      ruleForm[key] = {
        enabled: false,
        maxRetries: 3,
        interval: 5,
        failureAction: 'notify'
      }
    } else {
      ruleForm[key] = ''
    }
  })
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(ruleForm, row)
  dialogVisible.value = true
}

// 处理复制
const handleCopy = (row) => {
  dialogType.value = 'create'
  const copyData = JSON.parse(JSON.stringify(row))
  delete copyData.id
  copyData.name = `${copyData.name}_复制`
  Object.assign(ruleForm, copyData)
  dialogVisible.value = true
}

// 处理删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该规则吗？', '提示', {
      type: 'warning'
    })
    await deleteRule(row.id)
    ElMessage.success('删除成功')
    loadRuleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理批量删除
const handleBatchDelete = async () => {
  if (!selectedRules.value.length) return
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRules.value.length} 条规则吗？`,
      '提示',
      { type: 'warning' }
    )
    await batchDeleteRules(selectedRules.value.map(rule => rule.id))
    ElMessage.success('批量删除成功')
    loadRuleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 处理批量启用
const handleBatchEnable = async () => {
  if (!selectedRules.value.length) return
  
  try {
    await batchUpdateRuleStatus(
      selectedRules.value.map(rule => rule.id),
      'enabled'
    )
    ElMessage.success('批量启用成功')
    loadRuleList()
  } catch (error) {
    console.error('批量启用失败:', error)
    ElMessage.error('批量启用失败')
  }
}

// 处理批量禁用
const handleBatchDisable = async () => {
  if (!selectedRules.value.length) return
  
  try {
    await batchUpdateRuleStatus(
      selectedRules.value.map(rule => rule.id),
      'disabled'
    )
    ElMessage.success('批量禁用成功')
    loadRuleList()
  } catch (error) {
    console.error('批量禁用失败:', error)
    ElMessage.error('批量禁用失败')
  }
}

// 处理条件类型变化
const handleConditionTypeChange = () => {
  // 重置条件相关字段
  const condition = ruleForm.condition
  Object.keys(condition).forEach(key => {
    if (key !== 'type' && key !== 'logic' && key !== 'conditions') {
      condition[key] = ''
    }
  })
  if (condition.type === 'combination') {
    condition.conditions = []
  }
}

// 处理子条件类型变化
const handleSubConditionTypeChange = (index) => {
  const condition = ruleForm.condition.conditions[index]
  Object.keys(condition).forEach(key => {
    if (key !== 'type') {
      condition[key] = ''
    }
  })
}

// 添加子条件
const addSubCondition = () => {
  ruleForm.condition.conditions.push({
    type: '',
    timeType: '',
    time: null,
    period: '',
    relativeValue: 1,
    relativeUnit: 'minutes',
    event: '',
    field: '',
    operator: '',
    value: ''
  })
}

// 移除子条件
const removeSubCondition = (index) => {
  ruleForm.condition.conditions.splice(index, 1)
}

// 处理重试策略变化
const handleRetryStrategyChange = (val) => {
  if (!val) {
    ruleForm.retryStrategy = {
      enabled: false,
      maxRetries: 3,
      interval: 5,
      failureAction: 'notify'
    }
  }
}

// 保存规则
const saveRule = async () => {
  if (!ruleFormRef.value) return
  
  try {
    await ruleFormRef.value.validate()
    saving.value = true
    
    if (dialogType.value === 'create') {
      await createRule(ruleForm)
      ElMessage.success('创建成功')
    } else {
      await updateRule(ruleForm)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    loadRuleList()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    saving.value = false
  }
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  loadRuleList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadRuleList()
}

// 获取消息类型标签
const getMessageTypeLabel = (type) => {
  const found = messageTypes.find(item => item.value === type)
  return found ? found.label : type
}

// 获取优先级标签
const getPriorityLabel = (priority) => {
  const labelMap = {
    urgent: '紧急',
    high: '高',
    medium: '中',
    low: '低'
  }
  return labelMap[priority] || priority
}

// 获取优先级类型
const getPriorityType = (priority) => {
  const typeMap = {
    urgent: 'danger',
    high: 'warning',
    medium: 'info',
    low: ''
  }
  return typeMap[priority] || ''
}

// 获取渠道标签
const getChannelLabel = (channel) => {
  const labelMap = {
    email: '邮件',
    sms: '短信',
    wecom: '企业微信',
    dingtalk: '钉钉',
    feishu: '飞书'
  }
  return labelMap[channel] || channel
}

// 获取渠道类型
const getChannelType = (channel) => {
  const typeMap = {
    email: 'success',
    sms: 'warning',
    wecom: 'primary',
    dingtalk: 'info',
    feishu: 'danger'
  }
  return typeMap[channel] || ''
}

// 格式化条件显示
const formatCondition = (condition) => {
  if (!condition) return ''
  
  const { type, timeType, time, period, relativeValue, relativeUnit, event, field, operator, value, logic, conditions } = condition
  
  switch (type) {
    case 'time':
      if (timeType === 'fixed') {
        return `固定时间：${time}`
      } else if (timeType === 'period') {
        return `周期时间：${period} ${time}`
      } else {
        return `相对时间：${relativeValue}${relativeUnit}`
      }
    case 'event':
      return `事件：${event}`
    case 'data':
      return `数据：${field} ${operator} ${value}`
    case 'combination':
      return `组合条件：${logic === 'and' ? '且' : '或'} (${conditions.length}个子条件)`
    default:
      return ''
  }
}
</script>

<style lang="scss" scoped>
.notification-rule {
  padding: 20px;

  .operation-bar {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .search-form {
      flex: 1;
      margin-right: 20px;
    }

    .operation-buttons {
      display: flex;
      gap: 10px;
    }
  }

  .rule-table {
    .channel-tag {
      margin-right: 5px;
      margin-bottom: 5px;
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .condition-builder {
    display: flex;
    flex-direction: column;
    gap: 10px;

    .sub-condition {
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 10px;
      border: 1px dashed #dcdfe6;
      border-radius: 4px;
    }
  }

  .retry-strategy {
    margin-top: 10px;
    padding: 10px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;

    .unit {
      margin-left: 5px;
      color: #909399;
    }
  }
}
</style> 